package com.jeeplus.test.education.util;

import com.alibaba.excel.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SmartFieldConverter {
    // 特殊字段映射表（覆盖自动转换）
    private static final Map<String, String> SPECIAL_MAPPING = new HashMap<>();
    // 转换缓存
    private static final Map<String, String> CONVERSION_CACHE = new ConcurrentHashMap<>();

    // 添加例外映射（key: Java字段名, value: 数据库列名）
    static {
        //录取信息
        SPECIAL_MAPPING.put("totalScore", "total_score");
        SPECIAL_MAPPING.put("admissionDate", "admission_date");
        SPECIAL_MAPPING.put("admissionVolunteerCode", "admission_volunteer_code");
        SPECIAL_MAPPING.put("artCategory", "art_category");
        SPECIAL_MAPPING.put("subjectMatter", "subject_matter");
        SPECIAL_MAPPING.put("sportsLevel", "sports_level");
        SPECIAL_MAPPING.put("bonusPoints", "bonus_points");
        SPECIAL_MAPPING.put("policyDivision", "policy_division");
        SPECIAL_MAPPING.put("canBeDowngraded", "can_be_downgraded");
        SPECIAL_MAPPING.put("specialDivision", "special_division");
        SPECIAL_MAPPING.put("discountPoints", "discount_points");
        SPECIAL_MAPPING.put("takingCareOfPoints", "taking_care_of_points");
        SPECIAL_MAPPING.put("careForTheTarget", "care_for_the_target");
        SPECIAL_MAPPING.put("additionalTestScore", "additional_test_score");
        SPECIAL_MAPPING.put("minLanguage", "min_language");
        SPECIAL_MAPPING.put("archivalNum", "archival_num");
        SPECIAL_MAPPING.put("caseTitle", "case_title");
        SPECIAL_MAPPING.put("fileTitle", "file_title");
        SPECIAL_MAPPING.put("saveLocation", "save_location");
        SPECIAL_MAPPING.put("pageLocation", "page_location");
        SPECIAL_MAPPING.put("pageNum", "page_num");
        SPECIAL_MAPPING.put("examineeNum", "examinee_num");
        SPECIAL_MAPPING.put("admissionNum", "admission_num");
        SPECIAL_MAPPING.put("politicalOutlook", "political_outlook");
        SPECIAL_MAPPING.put("idCard", "id_card");
        SPECIAL_MAPPING.put("planNature", "plan_nature");
        SPECIAL_MAPPING.put("admissionSchools", "admission_schools");
        SPECIAL_MAPPING.put("admissionAcademy", "admission_academy");
        SPECIAL_MAPPING.put("admissionMajor", "admission_major");
        SPECIAL_MAPPING.put("admissionTime", "admission_time");
        SPECIAL_MAPPING.put("educationalSystem", "educational_system");
        SPECIAL_MAPPING.put("learningForms", "learning_forms");
        SPECIAL_MAPPING.put("examineeSort", "examinee_sort");
        SPECIAL_MAPPING.put("graduationSchool", "graduation_school");
        SPECIAL_MAPPING.put("sourceArea", "source_area");
        SPECIAL_MAPPING.put("areaName", "area_name");
        SPECIAL_MAPPING.put("homeAddress", "home_address");
        SPECIAL_MAPPING.put("postalCode", "postal_code");
        SPECIAL_MAPPING.put("phoneNum", "phone_num");
        SPECIAL_MAPPING.put("infoSource", "info_source");
        SPECIAL_MAPPING.put("classId", "class_id");
        SPECIAL_MAPPING.put("officeId", "office_id");
        SPECIAL_MAPPING.put("examineeSort", "examinee_sort");

        //学籍信息
        SPECIAL_MAPPING.put("serialNumber", "serial_number");
        SPECIAL_MAPPING.put("collegeName", "college_name");
        SPECIAL_MAPPING.put("departmentName", "department_name");
        SPECIAL_MAPPING.put("majorCode", "major_code");
        SPECIAL_MAPPING.put("majorName", "major_name");
        SPECIAL_MAPPING.put("classId", "class_id");
        SPECIAL_MAPPING.put("examTicketNumber", "exam_ticket_number");
        SPECIAL_MAPPING.put("studentId", "student_id");
        SPECIAL_MAPPING.put("birthDate", "birth_date");
        SPECIAL_MAPPING.put("politicalStatus", "political_status");
        SPECIAL_MAPPING.put("idCardNumber", "id_card_number");
        SPECIAL_MAPPING.put("educationLevel", "education_level");
        SPECIAL_MAPPING.put("studyForm", "study_form");
        SPECIAL_MAPPING.put("academicSystem", "academic_system");
        SPECIAL_MAPPING.put("enrollmentDate", "enrollment_date");
        SPECIAL_MAPPING.put("studentSource", "student_source");
        SPECIAL_MAPPING.put("areaCode", "area_code");
        SPECIAL_MAPPING.put("responsiblePerson", "responsible_person");
        SPECIAL_MAPPING.put("recordDate", "record_date");
        SPECIAL_MAPPING.put("archiveUnit", "archive_unit");
        SPECIAL_MAPPING.put("transferPerson", "transfer_person");
        SPECIAL_MAPPING.put("transferTime", "transfer_time");
        SPECIAL_MAPPING.put("archiveNumber", "archive_number");
        SPECIAL_MAPPING.put("caseTitle", "case_title");
        SPECIAL_MAPPING.put("documentTitle", "document_title");
        SPECIAL_MAPPING.put("pageLocation", "page_location");
        SPECIAL_MAPPING.put("sourceRemark", "source_remark");
        SPECIAL_MAPPING.put("sysName", "sys_name");
        SPECIAL_MAPPING.put("schoolYear", "school_year");
        SPECIAL_MAPPING.put("idNo", "id_no");
        SPECIAL_MAPPING.put("academicDegree", "academic_degree");
        SPECIAL_MAPPING.put("registrationStatus", "registration_status");
        SPECIAL_MAPPING.put("graduationTime", "graduation_time");
        SPECIAL_MAPPING.put("changeTime", "change_time");
        SPECIAL_MAPPING.put("changeCategory", "change_category");
        SPECIAL_MAPPING.put("nameBeforeChange", "name_before_change");
        SPECIAL_MAPPING.put("nameChanged", "name_changed");

        //档案信息
        SPECIAL_MAPPING.put("classId", "class_id");
        SPECIAL_MAPPING.put("studentId", "student_id");
        SPECIAL_MAPPING.put("materialId", "material_id");
        SPECIAL_MAPPING.put("materialSort", "material_sort");
        SPECIAL_MAPPING.put("materialName", "material_name");
        SPECIAL_MAPPING.put("responsiblePerson", "responsible_person");
        SPECIAL_MAPPING.put("dateTime", "date_time");
        SPECIAL_MAPPING.put("pageCount", "page_count");
        SPECIAL_MAPPING.put("archiveUnit", "archive_unit");
        SPECIAL_MAPPING.put("transferTime", "transfer_time");
        SPECIAL_MAPPING.put("archivalStatus", "archival_status");
        SPECIAL_MAPPING.put("unitLeader", "unit_leader");
        SPECIAL_MAPPING.put("archiveManager", "archive_manager");
        SPECIAL_MAPPING.put("collegeName", "college_name");
        SPECIAL_MAPPING.put("majorName", "major_name");
        SPECIAL_MAPPING.put("candidateNumber", "candidate_number");
        SPECIAL_MAPPING.put("originPlace", "origin_place");
        SPECIAL_MAPPING.put("admissionTicketNumber", "admission_ticket_number");
        SPECIAL_MAPPING.put("idNumber", "id_number");
        SPECIAL_MAPPING.put("storageLocation", "storage_location");
        SPECIAL_MAPPING.put("archiveNumber", "archive_number");
        SPECIAL_MAPPING.put("caseTitle", "case_title");
        SPECIAL_MAPPING.put("fileTitle", "file_title");
        SPECIAL_MAPPING.put("pageNumber", "page_number");
        SPECIAL_MAPPING.put("informationSource", "information_source");
        SPECIAL_MAPPING.put("batchId", "batch_id");
        SPECIAL_MAPPING.put("fileId", "file_id");
        SPECIAL_MAPPING.put("createTime", "create_time");
        SPECIAL_MAPPING.put("storageAddress", "storage_address");
        SPECIAL_MAPPING.put("retentionPeriod", "retention_period");
        SPECIAL_MAPPING.put("receptionTime", "reception_time");


        //毕业信息
        SPECIAL_MAPPING.put("examineeNum", "examinee_num");
        SPECIAL_MAPPING.put("admissionNum", "admission_num");
        SPECIAL_MAPPING.put("studentId", "student_id");
        SPECIAL_MAPPING.put("politicalOutlook", "political_outlook");
        SPECIAL_MAPPING.put("idCard", "id_card");
        SPECIAL_MAPPING.put("majorCode", "major_code");
        SPECIAL_MAPPING.put("majorName", "major_name");
        SPECIAL_MAPPING.put("educationalSystem", "educational_system");
        SPECIAL_MAPPING.put("learningForms", "learning_forms");
        SPECIAL_MAPPING.put("submitType", "submit_type");
        SPECIAL_MAPPING.put("enrollmentDate", "enrollment_date");
        SPECIAL_MAPPING.put("graduateDate", "graduate_date");
        SPECIAL_MAPPING.put("graduateConclusion", "graduate_conclusion");
        SPECIAL_MAPPING.put("certificateNo", "certificate_no");
        SPECIAL_MAPPING.put("certificateDate", "certificate_date");
        SPECIAL_MAPPING.put("degreeLevel", "degree_level");
        SPECIAL_MAPPING.put("degreeType", "degree_type");
        SPECIAL_MAPPING.put("thesisTitle", "thesis_title");
        SPECIAL_MAPPING.put("degreeNo", "degree_no");
        SPECIAL_MAPPING.put("degreeDate", "degree_date");
        SPECIAL_MAPPING.put("archiveNumber", "archive_number");
        SPECIAL_MAPPING.put("caseTitle", "case_title");
        SPECIAL_MAPPING.put("documentTitle", "document_title");
        SPECIAL_MAPPING.put("storageLocation", "storage_location");
        SPECIAL_MAPPING.put("pageLocation", "page_location");
        SPECIAL_MAPPING.put("pageNumber", "page_number");
        SPECIAL_MAPPING.put("responsiblePerson", "responsible_person");
        SPECIAL_MAPPING.put("dateTime", "date_time");
        SPECIAL_MAPPING.put("pageCount", "page_count");
        SPECIAL_MAPPING.put("archiveUnit", "archive_unit");
        SPECIAL_MAPPING.put("transferTime", "transfer_time");
        SPECIAL_MAPPING.put("informationSource", "information_source");
        SPECIAL_MAPPING.put("fileStatus", "file_status");
        SPECIAL_MAPPING.put("fileRemark", "file_remark");
        SPECIAL_MAPPING.put("sysName", "sys_name");
        SPECIAL_MAPPING.put("collegeName", "college_name");
        SPECIAL_MAPPING.put("graduationConclusion", "graduation_conclusion");
        SPECIAL_MAPPING.put("academicDegree", "academic_degree");
    }

    /**
     * 智能转换字段名（自动检测驼峰并转换）
     */
    public static String convert(String fieldName) {
        if (StringUtils.isBlank(fieldName)) {
            return fieldName;
        }

        return CONVERSION_CACHE.computeIfAbsent(fieldName, key -> {
            // 1. 检查特殊映射
            if (SPECIAL_MAPPING.containsKey(key)) {
                return SPECIAL_MAPPING.get(key);
            }

            // 2. 已经是下划线命名则直接返回
            if (key.contains("_")) {
                return key;
            }

            // 3. 自动驼峰转下划线
            return convertCamelToUnderscore(key);
        });
    }

    /**
     * 驼峰转下划线命名
     */
    private static String convertCamelToUnderscore(String camel) {
        StringBuilder result = new StringBuilder();
        result.append(Character.toLowerCase(camel.charAt(0)));

        for (int i = 1; i < camel.length(); i++) {
            char ch = camel.charAt(i);
            if (Character.isUpperCase(ch)) {
                result.append('_').append(Character.toLowerCase(ch));
            } else {
                result.append(ch);
            }
        }
        return result.toString();
    }
}
